#!/usr/bin/python3
# coding:utf-8
import os
import sys
import getopt

default_config = {
    "src_path": "/autocity/data/logs",
    "dst_path": "/mnt/bak",
    # "src_path": "/autocity/liuj/logs",
    # "dst_path": "/autocity/liuj/bak",
    "exclude_path": ["latest"],
}


def help():
    str = """
-h --help: help帮助
-s --src: 源目录
-d --dst: 目标目录
-e --exclude: 排除的目录
"""
    print(str)


def init_exclude_path(config):
    exclude_path = "%s/%s" % (config["src_path"], config["exclude_path"][0])
    exclude_real_path = os.path.basename(os.path.realpath(exclude_path))
    return [config["exclude_path"][0], exclude_real_path]


def parse_opt():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "s:d:e:h", ["src=", "dst=", "exclude=", "help"]
        )
    except getopt.GetoptError as err:
        print(err)
        help()
        sys.exit(2)
    src_path = default_config["src_path"]
    dst_path = default_config["dst_path"]
    exclude_path = init_exclude_path(default_config)
    for opt, opt_arg in opts:
        if opt in ("-s", "--src"):
            src_path = opt_arg
        elif opt in ("-d", "--dst"):
            dst_path = opt_arg
        elif opt in ("-e", "--exclude"):
            exclude_path += opt_arg.split()
        else:
            assert False, "未知参数"
    print(f"--src:{src_path} , --dst:{dst_path}, --exclude:{exclude_path}")
    return src_path, dst_path, exclude_path


def run_rsync_cmd(src_path, dst_path, exclude_path):
    exclude_list = ",".join(exclude_path)
    cmd = "rsync -rPL --exclude={%s} %s %s" % (exclude_list, src_path, dst_path)
    print(f"cmd= {cmd}")
    os.system(cmd)


def main():
    src_path, dst_path, exclude_path = parse_opt()
    run_rsync_cmd(src_path, dst_path, exclude_path)


if __name__ == "__main__":
    main()
